const newUserActiveModel = require("../model/newUserActive");
const signModel = require("../model/sign");
const RedisLock = require('../tools/redisLock')(cache); //redis锁，解决并发
exports.addNewUserSharTextRecord = async (unionId, openId, dateStr) => {
    const pool = await mysqlUtil();
    await pool.beginTransaction();
    try {
        /**
         * 查询用户信息，判断是否是新用户
         */
        const userInfo = await newUserActiveModel.queryUserInfo(pool, openId);
        if (userInfo && userInfo.idcardNum) {
            let nowDateStr = moment().format('YYYYMMDDHHmmss');
            //查询合同模板

            //防止并发，redis加锁
            const lock_count_key = 'new:sharetxt:500',
                ttlTime = 3000;
            const countLock = await RedisLock.lock(lock_count_key, ttlTime);

            //1.查询活动信息配置
            const activeCouldModInfo = await newUserActiveModel.h5activeConfig(pool, 1);
            console.log(22, '新用户分享文章配置信息', activeCouldModInfo);

            //2.用户已经办理的合同模板信息
            const activeCouldMouldId = activeCouldModInfo.additionalParameter;
            const contractCouldModInfo = await newUserActiveModel.getContractMouldIdByIdCardNum(pool, userInfo.idcardNum, activeCouldMouldId);
            console.log('查询出来的合同模板信息', contractCouldModInfo)

            //3.判断用户是否可以参加活动
            let isNewUserFlag = ((contractCouldModInfo && contractCouldModInfo.contractMouldId || '') == activeCouldMouldId);
            let activeOk = false;
            if (isNewUserFlag) {
                let configActiveTimeIsOk = activeCouldModInfo.startTime <= nowDateStr && activeCouldModInfo.endTime > nowDateStr;
                let createAisTimeok = nowDateStr < (moment(contractCouldModInfo.createTime, 'YYYYMMDDHHmmss').add(activeCouldModInfo.activeDays - 1, 'days').format('YYYYMMDD')) + '235959';
                activeOk = configActiveTimeIsOk && createAisTimeok;
                console.log(37, '今天的日期---dateStr---', dateStr, '是否可参加活动', activeOk, (moment(contractCouldModInfo.createTime, 'YYYYMMDDHHmmss').add(activeCouldModInfo.activeDays - 1, 'days').format('YYYYMMDD')) + '235959');
            };
            console.log('新用户分享文章，判断是否是新用户', isNewUserFlag, openId, '新用户合同模板信息', contractCouldModInfo, '文章新用户活动配置的合同模板', activeCouldMouldId);


            const redEnvlopRecord = await newUserActiveModel.hasNewUserDateRedEnvlopRecord(pool, userInfo.idcardNum, dateStr.substring(0, 8), 'newUserActive', activeCouldMouldId);
            console.log('当期日期红包记录：', unionId, openId, dateStr.substring(0, 8), redEnvlopRecord);

            //当天没有转发过，记录到发放红包h5_red_record表记录中,供common/newUserSubration.js定时任务发放红包
            if (!redEnvlopRecord && isNewUserFlag && activeCouldModInfo.activeCountLimit > 0 && activeOk) {
                //红包发放记录
                const addRedEnvlopRecordPromise = signModel.addRedEnvlopRecord(pool, {
                    open_id: openId,
                    union_id: unionId,
                    create_time: dateStr,
                    date_str: dateStr.substring(0, 8),
                    status: 0, //默认转发文章后，未发放红包,
                    amount: activeCouldModInfo.redAmount,
                    active_type: 'newUserActive',
                    contract_mould_id: activeCouldMouldId,
                    idcard_num: userInfo.idcardNum
                })
                //更新活动限制数量
                const updateH5activeConfigresPromise = newUserActiveModel.updateH5activeConfig(pool, 1, 1);
                const [addRedEnvlopRecord, updateH5activeConfigres] = await Promise.all([addRedEnvlopRecordPromise, updateH5activeConfigresPromise])
                console.log('插入红包记录结果', addRedEnvlopRecord, '新用户更新活动数量', updateH5activeConfigres)
            }
            //redis解锁
            await countLock.unlock();
        }

        const addSharTextRecordResult = await signModel.addSharTextRecord(pool, {
            open_id: openId,
            union_id: unionId,
            create_time: dateStr,
            active_type: 'newUserActive'
        })

        await pool.commit();
        return {
            // isFocusWxPub: true,
            addSharTextRecordResult
        }
    } catch (error) {
        await pool.rollback();
        throw error;
    } finally {
        pool.close();
    }
}

//查询红包记录发放结果
exports.queryDateStrRedEnvByStatusNewUserActive = async (status = 0, dataStr) => {
    const pool = await mysqlUtil();
    const userArray = await newUserActiveModel.queryDateStrRedEnvByStatusNewUserActive(pool, status, dataStr);
    pool.close();
    return userArray;
}

exports.batchUpdateNewUserRedEnvopStatus = async (status, successSendEnvLopOpenIds, dataStr) => {
    const pool = await mysqlUtil();
    const result = await newUserActiveModel.batchUpdateNewUserRedEnvopStatus(pool, status, successSendEnvLopOpenIds, dataStr);
    pool.close();
    return result;
}

exports.getH5activeConfig = async (id) => {
    const pool = await mysqlUtil();
    const result = await newUserActiveModel.h5activeConfig(pool, id);
    pool.close();
    return result;
}